import { Component, OnInit } from '@angular/core';
import {UserService} from "../user.service";
import {Response} from "@angular/http";

@Component({
  selector: 'app-user-manager',
  templateUrl: './user-manager.component.html',
  styleUrls: ['./user-manager.component.css']
})
export class UserManagerComponent implements OnInit {

  constructor(
    private userService:UserService,
  ) {}

  ngOnInit() {
    this.getAccountList();
    this.getRoles();
  }

  accountList:any;
  getAccountList(){
    let accountInfo = {name:"",statusName:""};
    this.userService.getAccountList(accountInfo)
      .subscribe((res:Response)=>{
        let data = res.json();
        console.log("list:",data);
        this.accountList = data.value;
      });
  }

  /**
   * 禁用账户
   * @param code
   */
  closeAccount(code){
    console.log("code:",code);
    let accountInfo = {code:code,status:1,properties:{updateStatus:true}};
    this.userService.updateStatus(accountInfo)
      .subscribe((res:Response)=>{
        let data = res.json();
        if (data.success){
          this.getAccountList();
        }
      })
  }

  /**
   * 启用账户
   * @param code
   * @constructor
   */
  ActiveAccount(code){
    let accountInfo = {code:code,status:0,properties:{updateStatus:true}};
    this.userService.updateStatus(accountInfo)
      .subscribe((res:Response)=>{
        let data = res.json();
        if (data.success){
          this.getAccountList();
        }
      })
  }
  showRoleFlag:boolean = false;
  currentAccountCode:string;
  showRoleDialog(code){
    this.showRoleFlag = true;
    this.currentAccountCode = code;
    //初始化
    this.currentRoleCode = this.roles[0].code;
  }
  updateRole(){
    console.log("updateRole:",this.currentAccountCode+this.currentRoleCode);
    this.showRoleFlag = false;
    let accountInfo = {code:this.currentAccountCode,roles:[{code:this.currentRoleCode}],properties:{updateRole:true}};
    this.userService.updateRole(accountInfo)
      .subscribe((res:Response)=>{
        let data = res.json();
        console.log("updateRole:",data.value);
        this.getAccountList();
      });
  }
  roles:any;
  currentRoleCode:any;
  getRoles(){
    let roleInfo = {properties:{code_not_equal:'admin'}};
    this.userService.getRoles(roleInfo)
      .subscribe((res:Response)=>{
        let data = res.json();
        console.log("roles:",data.value);
        this.roles = data.value;
        //初始化
        this.currentRoleCode = this.roles[0].code;
      });
  }

}
class accountInfo{
  code:string;
  name:string;
  statusName:string;
}
